import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import Element from './plugins/element'
import XuTable from './components/xu-table'
import { UserGetterEnum } from './_/vue/store/user'
import axios from 'axios'

Vue.use(Element)
Vue.component('xu-table', XuTable)

Vue.prototype.$goBack = () => {
  router.back()
}

function getCommonConfig () {
  return new Promise((resolve, reject) => {
    axios
      .get('/common.config.json')
      .then(({ data }) => {
        for (const key in data) {
          Vue.prototype[`$${key}`] = data[key]
        }
        resolve()
      })
      .catch(error => {
        console.log(error)
        return reject(error)
      })
  })
}
async function init () {
  await getCommonConfig()
}
Vue.config.productionTip = false

Vue.filter('order_status', val => {
  switch (val) {
    case '0':
      return '待支付'
    case '1':
      return '待发货'
    case '2':
      return '待收货'
    case '3':
      return '已取消'
    case '4':
      return '已完成'
    default:
      return '-'
  }
})

Vue.filter('sex', val => {
  switch (val) {
    case '0':
      return '保密'
    case '1':
      return '男'
    case '2':
      return '女'
  }
})

Vue.filter('order_type', val => {
  return val === 'course' ? '课程' : '会员卡'
})

Vue.filter('vip_expire', val => {
  return val === 0 ? '永久' : `${val}天`
})

// 路由监听器
router.beforeEach((to, from, next) => {
  // 判断是否登录
  const token = store.getters[UserGetterEnum.TOKEN]
  if (to.path === '/login') {
    next()
  } else {
    if (!token) {
      Element.Message.warning('请登录后访问')
      next('/login')
    } else {
      next()
    }
  }
})

new Vue({
  router,
  store,
  created () {
    init()
  },
  render: h => h(App)
}).$mount('#app')
